<template>
    <div></div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { tset_login, user_login } from "@/api/login";
import { showLoadingToast } from "vant";

//授权
const login = () => {
    let appid = "wwdc0bc731d475dfb8";
    let redirect_uri = "https://wechatwork.ihg.com.cn/static/amp/index.html";
    let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${encodeURI(appid)}&redirect_uri=${encodeURI(
        redirect_uri
    )}&response_type=code&scope=snsapi_base#wechat_redirect`;
    window.location.replace(url);
};

//获取code
const getQueryVariable = (variable) => {
    const search = window.location.search || window.location.hash.split("?")[1] || "";
    const params = new URLSearchParams(search);
    return params.get(variable);
};

//测试登录
const testLogin = async (user_id) => {
    const res = await tset_login({ user_id: user_id });
    console.log(res);
    //存token
    sessionStorage.setItem("amp_token", res.data);
    //跳转到登录前的页面
    window.location.replace("/static/amp/#" + sessionStorage.getItem("amp_redirect"));
};

//登录
const getLogin = async (code) => {
    let res = await user_login({
        code: code,
    });
    //存token
    sessionStorage.setItem("amp_token", res.data);
    //跳转到登录前的页面
    window.location.replace("/static/amp/#" + sessionStorage.getItem("amp_redirect"));
};

onMounted(() => {
    /**
     * 此应用为直接访问地址进入详情 不需要直接上来走登录 所以在router.beforeEach中处理 记录了地址 没有token回先到登录 授权后继续访问之前的页面
     * 测试页面request_id
     * http://localhost:5173/static/amp/#/PermissionRequest?request_id=1234
     * http://localhost:5173/static/amp/#/UpdateRequest?request_id=1222
     * 测试user_id
     * 47686 刘洋
     * 18 吴丹
     *
     * 开发时 使用textLogin() 打包上线时 使用if else 逻辑
     */
    // testLogin(18);

    if (getQueryVariable("code")) {
        showLoadingToast({
            message: "加载中...",
            forbidClick: true,
        });
        getLogin(getQueryVariable("code"));
    } else {
        login();
    }
});
</script>
<style lang="scss" scoped></style>
